﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using trx2html.Parser;
using System.IO;

namespace trx2html
{
    internal class ReportGenerator
    {
        internal static Action<String, object[]> LogMessageProvider
        {
            set;
            private get;
        }

        static void LogMessage(String fmt,params object[] arguments){
            if (LogMessageProvider != null)
            {
                LogMessageProvider(fmt, arguments);
            }
            else
            {
                Console.WriteLine(fmt, arguments);
            }
        }

        internal static string GenerateReport(string fileName,string outputPath,string destFileName)
        {
            VersionFinder v = new VersionFinder();
            SupportedFormats f = v.GetFileVersion(fileName);
            if (f != SupportedFormats.vs2010)
            {
                LogMessage("File {0} is not a recognized as a valid trx. Only VS2010 are supported", fileName);
                return null;
            }
            else
            {
                LogMessage("Processing {0} trx file", f.ToString());

                TrxParser parser = new TrxParser();
                TestRunResult r = parser.Parse(fileName);
                string html = new HtmlConverter(r).GetHtml();

                string destFullFileName = fileName + ".htm";
                if (outputPath != null)
                {
                    DirectoryInfo di = new DirectoryInfo(outputPath);
                    if (!di.Exists)
                    {
                        LogMessage("Output Path {0} does not exist,Now begin creating...", outputPath);
                        EnsureFolderExisting(di);
                    }

                    if (destFileName != null)
                    {
                        destFullFileName = Path.Combine(outputPath, Path.GetFileName(destFileName));
                    }
                    else
                    {
                        destFullFileName = Path.Combine(outputPath, Path.GetFileName(fileName)) + ".htm";
                    }
                    
                }

                using (TextWriter file = File.CreateText(destFullFileName))
                {
                    file.Write(html);
                }

                LogMessage("Tranformation Succeed. OutputFile: " + destFullFileName + ".htm\n");
                return destFullFileName;
            }
        }

        static void EnsureFolderExisting(DirectoryInfo di)
        {
            Stack<DirectoryInfo> dirStack = new Stack<DirectoryInfo>();
            DirectoryInfo currentDir = di;
            while (!currentDir.Exists)
            {
                dirStack.Push(currentDir);
                currentDir = currentDir.Parent;
            }

            while (dirStack.Count > 0)
            {
                currentDir = dirStack.Pop();
                currentDir.Create();
            }

        }
    }
}
